"""
发布API路由
"""

from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from typing import List, Optional
from pydantic import BaseModel

from ..core.database import get_db, GeneratedContent, PublishRecord
from ..core.logger import app_logger
from ..publishers.manager import publisher_manager

router = APIRouter()


class PublishRequest(BaseModel):
    """发布请求模型"""
    content_ids: List[int]


@router.post("/publish", summary="发布内容")
async def publish_contents(
    request: PublishRequest,
    db: Session = Depends(get_db)
):
    """发布生成的内容到各平台"""
    
    results = {}
    
    for content_id in request.content_ids:
        content = db.query(GeneratedContent).filter(
            GeneratedContent.id == content_id
        ).first()
        
        if not content:
            results[str(content_id)] = {
                "status": "error",
                "message": "内容不存在"
            }
            continue
        
        try:
            # 使用发布器管理器发布内容
            publish_result = await publisher_manager.publish_to_platform(
                content.platform, 
                content.content,
                hashtags=content.hashtags
            )
            
            # 记录发布结果
            record = PublishRecord(
                content_id=content_id,
                platform=content.platform,
                platform_post_id=publish_result.get("data", {}).get("post_id", ""),
                status="success" if publish_result["success"] else "failed",
                error_message=publish_result.get("error", "")
            )
            db.add(record)
            
            # 更新内容状态
            content.status = "published" if publish_result["success"] else "failed"
            
            results[str(content_id)] = {
                "status": "success" if publish_result["success"] else "error",
                "platform": content.platform,
                "post_id": publish_result.get("data", {}).get("post_id", ""),
                "message": publish_result.get("error", "" if publish_result["success"] else "发布成功")
            }
            
        except Exception as e:
            app_logger.error(f"发布内容 {content_id} 失败: {str(e)}")
            
            # 记录失败
            record = PublishRecord(
                content_id=content_id,
                platform=content.platform,
                status="failed",
                error_message=str(e)
            )
            db.add(record)
            
            content.status = "failed"
            
            results[str(content_id)] = {
                "status": "error",
                "message": str(e)
            }
    
    db.commit()
    
    return {
        "status": "completed",
        "results": results
    }


@router.get("/platforms", summary="获取发布平台列表")
async def get_platforms():
    """获取可用的发布平台列表"""
    
    platform_info = publisher_manager.get_platform_info()
    
    return {
        "status": "success",
        "platforms": platform_info
    }


@router.post("/test-connections", summary="测试平台连接")
async def test_platform_connections():
    """测试所有平台的连接状态"""
    
    try:
        results = await publisher_manager.test_all_connections()
        
        total_platforms = len(results)
        connected_platforms = sum(1 for connected in results.values() if connected)
        
        return {
            "status": "success",
            "total_platforms": total_platforms,
            "connected_platforms": connected_platforms,
            "results": results
        }
        
    except Exception as e:
        app_logger.error(f"测试平台连接失败: {e}")
        return {
            "status": "error",
            "message": str(e)
        }


@router.post("/publish-multi", summary="发布到多个平台")
async def publish_to_multiple_platforms(
    content_ids: List[int],
    platforms: Optional[List[str]] = None,
    db: Session = Depends(get_db)
):
    """将内容发布到多个平台"""
    
    if not platforms:
        platforms = publisher_manager.get_available_platforms()
    
    results = {}
    
    for content_id in content_ids:
        content = db.query(GeneratedContent).filter(
            GeneratedContent.id == content_id
        ).first()
        
        if not content:
            results[str(content_id)] = {
                "status": "error",
                "message": "内容不存在"
            }
            continue
        
        try:
            # 发布到多个平台
            publish_result = await publisher_manager.publish_to_multiple_platforms(
                platforms,
                content.content,
                hashtags=content.hashtags
            )
            
            # 记录每个平台的发布结果
            for platform, platform_result in publish_result.get("results", {}).items():
                record = PublishRecord(
                    content_id=content_id,
                    platform=platform,
                    platform_post_id=platform_result.get("data", {}).get("post_id", ""),
                    status="success" if platform_result.get("success", False) else "failed",
                    error_message=platform_result.get("error", "")
                )
                db.add(record)
            
            # 更新内容状态
            if publish_result.get("successful_platforms", 0) > 0:
                content.status = "published"
            else:
                content.status = "failed"
            
            results[str(content_id)] = {
                "status": "success" if publish_result.get("success", False) else "partial",
                "total_platforms": publish_result.get("total_platforms", 0),
                "successful_platforms": publish_result.get("successful_platforms", 0),
                "failed_platforms": publish_result.get("failed_platforms", 0),
                "details": publish_result.get("results", {})
            }
            
        except Exception as e:
            app_logger.error(f"多平台发布内容 {content_id} 失败: {e}")
            
            # 记录失败
            for platform in platforms:
                record = PublishRecord(
                    content_id=content_id,
                    platform=platform,
                    status="failed",
                    error_message=str(e)
                )
                db.add(record)
            
            content.status = "failed"
            
            results[str(content_id)] = {
                "status": "error",
                "message": str(e)
            }
    
    db.commit()
    
    return {
        "status": "completed",
        "results": results
    }


@router.get("/records", summary="获取发布记录")
async def get_publish_records(
    platform: Optional[str] = None,
    status: Optional[str] = None,
    limit: int = 20,
    db: Session = Depends(get_db)
):
    """获取发布记录列表"""
    
    query = db.query(PublishRecord)
    
    if platform:
        query = query.filter(PublishRecord.platform == platform)
    
    if status:
        query = query.filter(PublishRecord.status == status)
    
    records = query.order_by(PublishRecord.created_at.desc()).limit(limit).all()
    
    return {
        "status": "success",
        "data": [
            {
                "id": record.id,
                "content_id": record.content_id,
                "platform": record.platform,
                "platform_post_id": record.platform_post_id,
                "status": record.status,
                "error_message": record.error_message,
                "created_at": record.created_at.isoformat()
            }
            for record in records
        ],
        "total": len(records)
    }